package com.dy.yunying.biz.controller.datacenter;

import cn.hutool.core.util.ArrayUtil;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.datacenter.vo.PlanAttrAnalyseSearchVo;
import com.dy.yunying.biz.service.datacenter.PlanAnalysisService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.ExportUtils;
import com.dy.yunying.biz.utils.MapUtils;
import com.pig4cloud.pig.api.vo.MaterialVo;
import com.pig4cloud.pig.api.vo.PlanBaseAttrVo;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 计划属性分析表相关接口
 */
@Slf4j
@RestController("planarr")
@RequestMapping("/dataCenter/planarr")
@RequiredArgsConstructor
public class PlanArrOveriewController {

	private final PlanAnalysisService planAnalysisService;

	/**
	 * 计划属性总记录数
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/count")
	public R countDataTotal(@Valid @RequestBody PlanAttrAnalyseSearchVo req) {
		if (!PlatformTypeEnum.containsType(String.valueOf(req.getCtype()))) {
			throw new BusinessException(String.format("渠道类型标识不合法【%s】", req.getCtype()));
		}
//		return adOverviewService.countDataTotal(req);
		return planAnalysisService.count(req);
	}

	/**
	 * 计划属性报表数据
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getStatistic")
	public R getStatistic(@Valid @RequestBody PlanAttrAnalyseSearchVo req) {
		if (!PlatformTypeEnum.containsType(String.valueOf(req.getCtype()))) {
			throw new BusinessException(String.format("渠道类型标识不合法【%s】", req.getCtype()));
		}
//		return adOverviewService.selectPlanAttrAnalyseReoport(null, req);
		return planAnalysisService.page(null, req);
	}

	/**
	 * 计划属性统计导出
	 *
	 * @param req
	 * @return
	 */
//	@SysLog("计划属性统计导出")
	@ResponseExcel(name = "计划属性统计导出", sheet = "计划属性统计导出")
	@RequestMapping("/excelStatistic")
	public R excelPlanStatistic(@Valid @RequestBody PlanAttrAnalyseSearchVo req, HttpServletResponse response, HttpServletRequest request) {
		try {
			if (!PlatformTypeEnum.containsType(String.valueOf(req.getCtype()))) {
				throw new BusinessException(String.format("渠道类型标识不合法【%s】", req.getCtype()));
			}
			String sheetName = "计划属性统计导出";
//			R result = adOverviewService.selectPlanAttrAnalyseReoport(null, req);
			R result = planAnalysisService.page(null, req);
			//list对象转listMap PlanTtAttrAnalyseReportVo
			List<Map<String, Object>> resultListMap = MapUtils.objectsToMaps((List) result.getData());
			if (CollectionUtils.isEmpty(resultListMap)) {
				throw new BusinessException("无数据");
			}

			// 导出汇总数据
			req.setQueryColumn(Constant.EMPTTYSTR);
			req.setCycleType(4);
//			List<Map<String, Object>> collectListMap = MapUtils.objectsToMaps((List<PlanBaseAttrVo>) adOverviewService.selectPlanAttrAnalyseReoport(null, req).getData());
			List<Map<String, Object>> collectListMap = MapUtils.objectsToMaps((List<PlanBaseAttrVo>) planAnalysisService.page(null, req).getData());
			for (Map<String, Object> map : collectListMap) {
				map.put(req.getColumns().split(",")[0], "汇总");
			}
			resultListMap.addAll(collectListMap);

			resultListMap.forEach(v -> {
				List<MaterialVo> vos = (List<MaterialVo>) v.get("materialVos");
				if (CollectionUtils.isNotEmpty(vos)) {
					v.put("materialVos", ArrayUtil.join(vos.stream().map(MaterialVo::getMName).toArray(), Constant.COMMA));
				} else {
					v.put("materialVos", Constant.EMPTTYSTR);
				}
				BigDecimal regPayRatio = (BigDecimal) v.get("regPayRatio");
				if (!Objects.isNull(regPayRatio)) {
					v.put("regPayRatio", String.format("%s%s", regPayRatio.doubleValue(), Constant.PERCENT));
				} else {
					v.put("regPayRatio", String.format("0%s", Constant.PERCENT));
				}
				BigDecimal roi1 = (BigDecimal) v.get("roi1");
				if (!Objects.isNull(regPayRatio)) {
					v.put("roi1", String.format("%s%s", roi1.doubleValue(), Constant.PERCENT));
				} else {
					v.put("roi1", String.format("0%s", Constant.PERCENT));
				}
				BigDecimal retention2Ratio = (BigDecimal) v.get("retention2Ratio");
				if (!Objects.isNull(regPayRatio)) {
					v.put("retention2Ratio", String.format("%s%s", retention2Ratio.doubleValue(), Constant.PERCENT));
				} else {
					v.put("retention2Ratio", String.format("0%s", Constant.PERCENT));
				}
				BigDecimal allRoi = (BigDecimal) v.get("allRoi");
				if (!Objects.isNull(regPayRatio)) {
					v.put("allRoi", String.format("%s%s", allRoi.doubleValue(), Constant.PERCENT));
				} else {
					v.put("allRoi", String.format("0%s", Constant.PERCENT));
				}

				BigDecimal createRoleRate = (BigDecimal) v.get("createRoleRate");
				if (!Objects.isNull(createRoleRate)) {
					v.put("createRoleRate", String.format("%s%s", createRoleRate.toString(), Constant.PERCENT));
				} else {
					v.put("createRoleRate", String.format("0%s", Constant.PERCENT));
				}

				BigDecimal certifiedRate = (BigDecimal) v.get("certifiedRate");
				if (!Objects.isNull(certifiedRate)) {
					v.put("certifiedRate", String.format("%s%s", certifiedRate.toString(), Constant.PERCENT));
				} else {
					v.put("certifiedRate", String.format("0%s", Constant.PERCENT));
				}
			});
			// 导出
			R re = ExportUtils.exportExcelData(request, response, String.format("计划属性统计导出-%s.xlsx", DateUtils.getCurrentTimeNoUnderline()), sheetName, req.getTitles(), req.getColumns(), resultListMap);
			if (re.getCode() == CommonConstants.FAIL) {
				throw new BusinessException(re.getMsg());
			}
		} catch (BusinessException e) {
			log.error("excelPlanStatistic is error", e);
			throw e;
		} catch (Exception e) {
			log.error("excelPlanStatistic is error", e);
			throw new BusinessException("导出异常");
		}
		return null;
	}

//	/**
//	 * 计划属性报表数据
//	 *
//	 * @param req
//	 * @return
//	 */
//	@ResponseBody
//	@GetMapping(value = "/getStatisticPage")
//	public R getStatisticPage(@Valid PlanAttrAnalyseSearchVo req) {
//		if (!PlatformTypeEnum.containsType(String.valueOf(req.getCtype()))) {
//			throw new BusinessException(String.format("渠道类型标识不合法【%s】", req.getCtype()));
//		}
//		return adOverviewService.selectPlanAttrAnalyseReoport(new Page(req.getCurrent(), req.getSize()), req);
//	}

}
